package com.LostAndFound.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.LostAndFound.domain.Root;
import com.LostAndFound.domain.User;
import com.LostAndFound.service.LoginService;


public class LoginServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	LoginService service = new LoginService();
	// 管理员登陆
	public void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Root root =null;
		root = service.findRootForLogin(username,password);
		if(root!=null){
			session.setAttribute("root", root);
			response.sendRedirect(request.getContextPath()+"/admin/00/home.jsp");
		}else {
			request.setAttribute("error", "账号或者密码错误");
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			request.getRequestDispatcher("/admin/login.jsp").forward(request, response);		
		}
	}
	// 用户登陆
	public void userLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user =null;
		user = service.findUserForLogin(username,password);
		boolean success = false;
		if(user!=null){
			// 用户存在，就直接跳转到用户的首页
			session.setAttribute("user", user);
			success = true;
		}else {
			// 否则，写回 json 
			success = false;
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
}